import 'package:changxindianzishangwu/dao/data_center_dao.dart';
import 'package:changxindianzishangwu/model/data_center_overview_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/common_page.dart';
import 'package:common_utils/common_utils.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import 'data_center_calendar_page.dart';

class DataCenterPage extends StatefulWidget {
  const DataCenterPage({Key key}) : super(key: key);

  @override
  _DataCenterPageState createState() => _DataCenterPageState();
}

class _DataCenterPageState extends State<DataCenterPage>
    with TickerProviderStateMixin {
  TextStyle _style(double s, color) {
    return TextStyle(fontSize: sp(s), color: color);
  }

  TabController tabController2;
  CenterOverviewData _overviewData; //数据概览
  CenterOverviewData _friendsData; //好友数据

  int _daysIndex = 0; //选择天数下标
  int _type = 0; //默认新增好友

  List<String> _titles = ["新增好友", "会话人数", "发送消息", "接收消息"];

  @override
  void initState() {
    super.initState();
    String time=formatDate(DateTime.now(), [yyyy,'-',mm,'-',dd]);
    getDataOverview(time,time); //数据概览
    getDataFriends(1); //昨天
    tabController2 = TabController(length: 4, vsync: this);
    tabController2.addListener(() {
      _type = tabController2.index;
      // print('----------切换:$_type');
    });
  }

  void getDataFriends(int startDays, {int type = 0}) async {
    EasyLoading.show();
    Duration sdays = Duration(days: startDays);
    var _model = await DataCenterDao.getDataOverview(sdays);
    EasyLoading.dismiss();
    if (_model is DataCenterOverviewModel) {
      setState(() {
        _friendsData = _model.data;
      });
    }else{
      toast("数据中心获取数据失败：${_model.resultMsg}");
    }
  }

  void getDataOverview(String startTime, String endTime) async {
    EasyLoading.show();
    var _model = await DataCenterDao.getDataOverview(
        null, startTime: startTime, endTime: endTime);
    EasyLoading.dismiss();
    if (_model is DataCenterOverviewModel) {
      setState(() {
        _overviewData = _model.data;
      });
    }else{
      toast("数据中心获取数据失败：${_model.resultMsg}");
    }

  }

  @override
  void dispose() {
    EasyLoading.dismiss();
    tabController2.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(
        context,
        "数据中心",
        rightWidget: Image.asset(
          "images/ic_caution.png",
          width: width(15),
          height: width(15),
        ),
        rightCallback: () {
          showCupertinoDialog(
              context: context,
              builder: (context) =>
                  UniversalView().getDialog(
                      context, "提示", AppString.sj_center_hint,
                      right: "知道了"));
        },
      ),
      body: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return <Widget>[
              SliverToBoxAdapter(
                child: _head(),
              ),
              SliverToBoxAdapter(
                child: _centerTab(), //好友数据 渠道数据 动态数据
              ),
              SliverPersistentHeader(
                pinned: true,
                delegate: StickyTabBarDelegate(
                  child: TabBar(
                    labelPadding: EdgeInsets.only(bottom: height(3)),
                    tabs: [
                      _msgTab(
                          "${_friendsData == null ? 0 : _friendsData
                              .friendsNum}",
                          _titles[0]),
                      _msgTab(
                          "${_friendsData == null ? 0 : _friendsData.msgSum}",
                          _titles[1]),
                      _msgTab(
                          "${_friendsData == null ? 0 : _friendsData
                              .sendMsgNum}",
                          _titles[2]),
                      _msgTab(
                          "${_friendsData == null ? 0 : _friendsData
                              .receiveNum}",
                          _titles[3]),
                    ],
                    controller: tabController2,
                    indicatorColor: AppColor.colorTheme,
                  ),
                ),
              ),
            ];
          },
          body: TabBarView(controller: tabController2, children: [
            // SizedBox(),
            // SizedBox(),
            // SizedBox(),
            // SizedBox(),
            ListWidget(0, _daysIndex),
            ListWidget(1, _daysIndex),
            ListWidget(2, _daysIndex),
            ListWidget(3, _daysIndex),
          ])),
    );
  }

  Container _msgTab(num, title) {
    return Container(
      padding: EdgeInsets.all(5),
      child: Column(
        children: [
          Text(
            num,
            style: _style(16, Colors.black),
          ),
          Text(
            title,
            style: _style(10, AppColor.colorGrey153),
          )
        ],
      ),
    );
  }

  //好友数据 渠道数据 动态数据
  _centerTab() {
    return Container(
      margin: EdgeInsets.only(top: width(10)),
      padding: EdgeInsets.only(
        left: width(15),
        right: width(15),
      ),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(6)),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                key: GlobalKey(),
                child: Center(
                  child: Container(
                      child: Text(
                        "好友数据",
                        style: _style(14, AppColor.colorTheme),
                      ),
                      padding: EdgeInsets.all(width(10)),
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: AppColor.colorTheme)))),
                ),
                flex: 1,
              ),
              _tab(),
              _tab()
            ],
          ),
          SizedBox(
            height: height(20),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _daysBtn(0, "昨天"),
              _daysBtn(1, "前7天"),
              _daysBtn(2, "前30天"),
            ],
          ),
          SizedBox(
            height: height(20),
          ),
        ],
      ),
    );
  }

  _tab() {
    return Expanded(
        key: GlobalKey(),
        child: InkWell(
          onTap: () {
            toast("暂未开放，敬请期待");
          },
          child: Container(
            child: Center(
              child: Text(
                "渠道数据",
                style: _style(14, AppColor.colorGrey153),
              ),
            ),
          ),
        ));
  }

  ///数据概览 头部
  Widget _head() {
    return Container(
      padding: EdgeInsets.only(
        bottom: width(20),
        left: width(15),
        top: width(15),
        right: width(15),
      ),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(6)),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  "数据概览",
                  style: _style(15, AppColor.colorDefaultText),
                ),
                flex: 1,
              ),
              InkWell(
                onTap: () {
                  Get.to(DataCenterCalendarPage()).then((value) {
                    if (value != null) {
                      getDataOverview(value.startTime,value.endTime);
                    }
                  });
                },
                child: Padding(
                  padding: const EdgeInsets.only(left: 15, bottom: 30),
                  child: Image.asset(
                    "images/ic_rl.png",
                    width: width(15),
                    height: width(15),
                  ),
                ),
              )
            ],
            crossAxisAlignment: CrossAxisAlignment.start,
          ),
          Row(
            children: [
              _kltab("${_overviewData == null ? 0 : _overviewData.friendsNum}",
                  _titles[0]),
              _kltab("${_overviewData == null ? 0 : _overviewData.msgSum}",
                  _titles[1]),
              _kltab("${_overviewData == null ? 0 : _overviewData.sendMsgNum}",
                  _titles[2]),
              _kltab("${_overviewData == null ? 0 : _overviewData.receiveNum}",
                  _titles[3]),
            ],
          )
        ],
      ),
    );
  }

  _kltab(num, title) {
    return Expanded(
      flex: 1,
      child: Column(
        children: [
          Text(
            num,
            style: _style(24, Colors.black),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 5),
            child: Text(
              title,
              style: _style(12, AppColor.colorGrey153),
            ),
          ),
        ],
      ),
    );
  }

  /// 中间日期 昨天 7天 30天
  Widget _daysBtn(index, title) {
    return InkWell(
      onTap: () {
        setState(() {
          if (_daysIndex == index) return;
          _daysIndex = index;
          int days = _daysIndex == 0
              ? 1
              : _daysIndex == 1
              ? 7
              : 30;
          getDataFriends(days);
        });
      },
      child: Container(
        width: width(70),
        height: width(25),
        child: Center(
          child: Text(
            title,
            style: _style(
                12, _daysIndex == index ? Colors.white : AppColor.colorGrey153),
          ),
        ),
        decoration: BoxDecoration(
            color: _daysIndex == index
                ? AppColor.colorTheme
                : AppColor.colorGrey245),
      ),
    );
  }
}

class ListWidget extends StatefulWidget {
  int index;
  int daysIndex;

  ListWidget(this.index, this.daysIndex, {Key key}) : super(key: key);

  @override
  _ListWidgetState createState() => _ListWidgetState();
}

class _ListWidgetState extends State<ListWidget>
    with AutomaticKeepAliveClientMixin {
  List<String> _titles = ["新增好友", "会话人数", "发送消息", "接收消息"];

  getDataList() async {
    int days = widget.daysIndex == 0
        ? 1
        : widget.daysIndex == 1
        ? 7
        : 30;
    Duration sdays = Duration(days: days);
    var result = await DataCenterDao.getDataList(sdays, widget.index);

    return result;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // print('------------加载列表${widget.index}');
    return FutureBuilder(
        future: getDataList(),
        builder: (context, sp) {
          if (sp.connectionState == ConnectionState.done ) {
            if (ObjectUtil.isEmpty(sp.data)) {
              return CommonPage.loading(() {}, state: PageState.PAGE_EMPTY);
            }
            if (sp.data is int) {
              return CommonPage.loading(() {},
                  state: PageState.PAGE_ERROR, title: "加载错误");
            } else {
                return Container(
                  padding: EdgeInsets.all(width(15)),
                  color: Colors.white,
                  child: CustomScrollView(
                    slivers: [
                      SliverToBoxAdapter(
                        child: Text(
                          _titles[widget.index],
                          style: TextStyle(
                              fontSize: 15, color: AppColor.colorDefaultText),
                        ),
                      ),
                      SliverToBoxAdapter(
                        child: _sliverItem("日期", _titles[widget.index]),
                      ),
                      SliverList(
                        key: UniqueKey(),
                        delegate: SliverChildBuilderDelegate(
                                (BuildContext content, int index) {
                              return _sliverItem(
                                  sp.data[index].time, sp.data[index].num);
                            }, childCount: sp.data.length),
                      )
                    ],
                  ),
                );
            }
          } else {
            return CommonPage.loading(() {}, state: PageState.PAGE_LOADING);
          }
        });
  }

  Widget _sliverItem(time, num) {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        children: [
          Expanded(
              flex: 1,
              child: Text(
                time,
                style:
                TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              )),
          Expanded(
              flex: 1,
              child: Text(
                num,
                style:
                TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              )),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(BuildContext context, double shrinkOffset,
      bool overlapsContent) {
    return Container(
      color: Theme
          .of(context)
          .backgroundColor,
      child: this.child,
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
